package org.zxp.onedoteight.stream;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: effectiveJava
 * @description:
 * @author: X-Pacific zhang
 * @create: 2020-08-30 21:58
 **/
public class TestStreamConRelation {
    public static void main(String[] args) {
        //总价 35
        List<VideoOrder> videoOrders1 = Arrays.asList(
                new VideoOrder("20190242812", "springboot教程", 3),
                new VideoOrder("20194350812", "微服务SpringCloud", 5),
                new VideoOrder("20190814232", "Redis教程", 9),
                new VideoOrder("20190523812", "网页开发教程", 9),
                new VideoOrder("201932324", "百万并发实战Netty", 9));
        //总价 54
        List<VideoOrder> videoOrders2 = Arrays.asList(
                new VideoOrder("2019024285312", "springboot教程", 3),
                new VideoOrder("2019081453232", "Redis教程", 9),
                new VideoOrder("20190522338312", "网页开发教程", 9),
                new VideoOrder("2019435230812", "Jmeter压力测试", 5),
                new VideoOrder("2019323542411", "Git+Jenkins持续集成", 7),
                new VideoOrder("2019323542424", "Idea全套教程", 21));


        //交集 通过filter过滤实现
        List<VideoOrder> intersectionList = videoOrders1.stream().filter(videoOrders2::contains).collect(Collectors.toList());
        System.out.println("交集=" + intersectionList);

        //差集1
        List<VideoOrder> diffList1 = videoOrders1.stream().filter(obj -> !videoOrders2.contains(obj)).collect(Collectors.toList());
        System.out.println("差集(1有2没有)=" + diffList1);
        //差集2
        List<VideoOrder> diffList2 = videoOrders2.stream().filter(obj -> !videoOrders1.contains(obj)).collect(Collectors.toList());
        System.out.println("差集(2有1没有)=" + diffList2);

        //并集
        List<VideoOrder> allVideoOrder = videoOrders1.parallelStream().collect(Collectors.toList());
        allVideoOrder.addAll(videoOrders2);
        System.out.println("并集 = " + allVideoOrder);

        //去重并集
        List<VideoOrder> allVideoOrderDistinct = allVideoOrder.stream().distinct().collect(Collectors.toList());
        System.out.println("去重并集 = " + allVideoOrderDistinct);
    }

    @Data
    @AllArgsConstructor
    private static class VideoOrder {
        private String tradeNo;
        private String title;
        private int money;

        /**
         * 重写equals的原因是：为了让title相等的订单就认为是相等的
         * 除此之外还要重写hashcode，因为对象比较替换为用title比较了，所以hashcode也要替换成title的hashcode
         *
         * @param obj
         * @return
         */
        @Override
        public boolean equals(Object obj) {
            if (obj instanceof VideoOrder) {
                VideoOrder o1 = (VideoOrder) obj;
                return title.equals(o1.getTitle());
            }
            return super.equals(obj);
        }

        @Override
        public int hashCode() {
            return title.hashCode();
        }
    }
}
